package com.test;

import com.test.entity.User;
import com.test.util.MyBatisUtil;
import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import java.util.List;

public class UserMybatis {
    private SqlSession sqlSession;
    private UserMapper userMapper;

    public void setUp() {
        sqlSession = MyBatisUtil.getSqlSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
        System.out.println("===== 开始执行MyBatis CRUD测试 =====");
    }

    public void insertUser() {
        // 构造方法参数name改为username
        User user = new User("张三", "zhangsan@example.com", 20);
        int result = userMapper.insertUser(user);
        sqlSession.commit();
        System.out.println("插入用户结果：" + (result > 0 ? "成功，ID为" + user.getId() : "失败"));
    }

    public void queryAllUsers() {
        List<User> userList = userMapper.queryUserList();
        System.out.println("查询到的用户列表：");
        for (User user : userList) {
            // 输出信息中name改为username，调用getUsername()方法
            System.out.println("ID：" + user.getId() + "，用户名：" + user.getName() + "，邮箱：" + user.getEamil() + "，年龄：" + user.getAge());
        }
    }

    public void queryUserById(int id) {
        User user = userMapper.queryUserById(id);
        System.out.println("根据ID查询用户结果：" + (user != null ? "存在，信息为" + user : "不存在"));
    }

    public void updateUser() {
        // 构造方法参数name改为username
        User user = new User("张三", "zhangsan_new@example.com", 21);
        user.setId(1);
        int result = userMapper.updateUser(user);
        sqlSession.commit();
        System.out.println("更新用户结果：" + (result > 0 ? "成功" : "失败"));
    }

    public void deleteUser(int id) {
        int result = userMapper.deleteUser(id);
        sqlSession.commit();
        System.out.println("删除用户结果：" + (result > 0 ? "成功" : "失败"));
    }

    public void tearDown() {
        if (sqlSession != null) {
            sqlSession.close();
        }
        System.out.println("===== CRUD测试结束 =====");
    }
}
